﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace EncoderFixer
{
    class EncoderFixer
    {
        private FileStream fileStream;
        private bool isDBBusy;                                          // file is busy
        private int bByte;                                              // consist read byte from file for checking
        private const int fileShift = 29;                               // shift in file
        private const int correctByte = 101;                            // correct byte        
        private const int timerStep = 10000;                            // timer step (10 000 ms default)
        //private const string dbPath = "X:\\TULA\\BV\\BVIN.DBF";        
        private const string dbPath = "C:\\TULA\\BV\\BVIN.DBF";         // path to file
        private bool canRead = true;

        private Thread tMonitoring;

        public void Start()
        {            
            tMonitoring.Start();
        }

        public void Stop()
        {
            tMonitoring.Abort();
        }

        public EncoderFixer()
        {            
            isDBBusy = false;
            tMonitoring = new Thread(new ThreadStart(ThreadProc));                        
        }
        private void ThreadProc()
        {
            while (tMonitoring.IsAlive)
            {
                Thread.Sleep(timerStep);                
                try
                {
                    ///* Trying to open file for read,
                    ///if it accessable, read byte what we need
                    fileStream = new FileStream(@dbPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    if (fileStream.CanRead)                    {
                        
                        fileStream.Seek(fileShift, SeekOrigin.Begin);
                        bByte = fileStream.ReadByte();
                        canRead = true;

                        if (isDBBusy)
                        {
                            isDBBusy = false;
                            WriteLog("DB is free");                            
                        }
                    }
                }
                catch (Exception)
                {                    
                    if (fileStream != null)
                        fileStream.Close();

                    if (!isDBBusy)
                    {                        
                        WriteLog("DB is Busy... probably someone opened it...");
                        isDBBusy = true;
                    }
                }
                finally
                {                   
                    if (fileStream != null)
                        fileStream.Close();
                    if (bByte != correctByte && canRead)
                    {
                        // send message to f01d, f03d
                        Process myProcess = Process.Start("cmd", "/C net send f03d 1D Byte is not 65, fixing...");
                        myProcess.Close();
                        myProcess = Process.Start("cmd", "/C net send f01d 1D Byte is not 65, fixing...");
                        myProcess.Close();

                        
                        /// try to fix not correct byte
                        try
                        {
                            fileStream = new FileStream(@dbPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                            fileStream.Seek(fileShift, SeekOrigin.Begin);
                            fileStream.WriteByte(correctByte);
                            WriteLog("Byte is not 65, fixing... Trying to fix...");

                        }
                        catch (Exception)
                        {
                            if (fileStream != null)
                                fileStream.Close();

                        }
                        finally
                        {
                            if (fileStream != null)
                                fileStream.Close();
                            if (isDBBusy)
                            {
                                isDBBusy = false;
                                WriteLog("DB is free");                            
                            }
                        }
                    }
                }
            }            
        }
        /// *
        /// super-meaga log-writer ))
        /// 
        private void WriteLog(string message)
        {
            DateTime dt;
            string t, msg;            
            try
            {
                dt = DateTime.Now;
                t = dt.ToString("[dd.MM.yyyy HH:mm:ss]: ");
                msg = t + message;
                FileStream fs = new FileStream("logfile.log", FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(msg);
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {

            }
        }
    }
}

















